package com.tensquare.base.controller;

import com.tensquare.base.pojo.Label;
import com.tensquare.base.service.LabelService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by WF on 2020/3/28 14:47
 */
@RestController
@RequestMapping("label")
@CrossOrigin
@RefreshScope      //此注解主要针对自定义配置使用spring-cloud-bus进行自动刷新
public class LabelController {
    @Autowired
    private LabelService labelService;
    @Value("${ip}")
    private String ip;
    //1.查询所有标签
    @GetMapping
    public Result findAll(){
        System.out.println("ip = " + ip);
        //1.1)查询所有的标签列表
        List<Label> labels = labelService.findAll();
        //1.2)返回result
        return new Result(true,StatusCode.OK,"查询标签列表成功！",labels);
    }
    //2.根据id查询
    @GetMapping("{labelId}")
    public Result findById(@PathVariable String labelId){
        //2.1)查询id查询标签对象
        Label label = labelService.findById(labelId);
        //2.2)返回
        return new Result(true,StatusCode.OK,"查询单个标签成功！",label);
    }
    //3.添加标签
    @PostMapping
    public Result add(@RequestBody Label label){
        try {
            //3.1)添加标签到数据库中
            labelService.add(label);
            //3.2)返回
            return new Result(true,StatusCode.OK,"添加标签成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"添加标签失败！");
        }
    }
    //4.修改标签
    @PutMapping("{labelId}")
    public Result update(@PathVariable String labelId,@RequestBody Label label){
        //4.1)修改标签
        //4.1.1)将标签id与label进行绑定
        label.setId(labelId);
        //4.1.2)开始修改
        labelService.update(label);
        //4.2)返回
        return new Result(true,StatusCode.OK,"修改标签成功！");
    }
    //5.根据id来删除标签
    @DeleteMapping("{labelId}")
    public Result delete(@PathVariable String labelId){
        //5.1)根据id删除标签
        labelService.delete(labelId);
        //5.2)返回
        return new Result(true,StatusCode.OK,"删除标签成功！");
    }
    //6.根据条件进行查询
    @PostMapping("search")
    public Result search(@RequestBody Label label){
        //6.1)根据条件进行查询
        List<Label> labelList = labelService.search(label);
        //6.2)返回
        return new Result(true,StatusCode.OK,"根据查询成功！",labelList);
    }
    //7.条件查询带分页
    @PostMapping("search/{page}/{size}")
    public Result search(@RequestBody Label label,@PathVariable int page,@PathVariable int size){
        //7.1)条件查询带分页
        PageResult pageResult = labelService.search(label,page,size);
        //7.2)返回
        return new Result(true,StatusCode.OK,"条件查询带分页成功！",pageResult);
    }
}
